import React, {useState} from 'react';
import InputButton from '../../component/InputButton';
import {View, InputItem, Button} from '@ant-design/react-native';
import {StyleSheet, Text} from 'react-native';
import Modal from '../../util/Modal';
import Toast from '../../component/Toast';
import axios from '../../http/http';
import useStorage from '../../hooks/storage';
import {TUserInfo} from '../../type/TUser';
const Email = ({navigation}) => {
  const [validCode, setValidCode] = useState('');
  const [newEmail, setNewEmail] = useState('');
  const userInfoStorage = useStorage<TUserInfo>('userInfo');
  const onButtonClick = async () => {
    const userInfo = await userInfoStorage.getItem();
    Modal('修改邮箱', () => {
      axios
        .post('/user/validEmailCode', {
          email: newEmail,
          code: validCode,
          id: userInfo!.id,
        })
        .then(res => {
          if (res.error === -1) {
            Toast.info(res.data);
            userInfoStorage.setItem({...userInfo, email: newEmail});
            navigation.pop();
          } else {
            Toast.info(res.message);
          }
        });
    });
  };
  const valid = async () => {
    Toast.loading('验证码发送中');
    const userInfo = await userInfoStorage.getItem();
    axios
      .post('/user/sendEmailCode', {
        id: userInfo!.id,
        email: newEmail,
      })
      .then(res => {
        Toast.removeAll();
        res.error === -1 ? Toast.info(res.data) : Toast.info(res.message);
      });
  };
  return (
    <View style={styles.email_box}>
      <InputItem
        clear
        value={newEmail}
        onChange={setNewEmail}
        labelNumber={3}
        placeholder="请输入用户名">
        新邮箱
      </InputItem>
      <InputButton
        value={validCode}
        onChange={setValidCode}
        disabled={!newEmail}
        valid={valid}
        title="验证码"
      />
      <Button
        type="primary"
        disabled={!validCode || !newEmail}
        onPress={onButtonClick}>
        更改邮箱
      </Button>
    </View>
  );
};
const styles = StyleSheet.create({
  email_box: {
    padding: 10,
  },
});
export default Email;
